<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <style>
    *{
      margin: 0;
      padding: 0;
      list-style: none;
      vertical-align: middle;
    }
    .viewport{
      width: 100%;
      overflow: hidden;
    }
    .viewport ul{
      position: relative;
      overflow: hidden;
    }
    .viewport li{
      float: left;
    }
    .viewport img{
      width: 100%;
    }
  </style>
</head>
<body>
  <div class="viewport">
    <ul>
      <li><a href="javascript:;"><img src="img/lb1.png" alt=""></a></li>
      <li><a href="javascript:;"><img src="img/lb2.png" alt=""></a></li>
      <li><a href="javascript:;"><img src="img/lb3.png" alt=""></a></li>
      <li><a href="javascript:;"><img src="img/lb4.png" alt=""></a></li>
    </ul>
  </div>
  <script>
    var ul = document.querySelector('ul');
    var cfirst_li = document.querySelector('ul li:first-child').cloneNode(true);
    var clast_li = document.querySelector('ul li:last-child').cloneNode(true);
    ul.appendChild(cfirst_li);
    ul.insertBefore(clast_li,document.querySelector('ul li:first-child'));
    
    //设置ul的宽度
    var imgs = document.querySelectorAll('img');
    var viewport = document.querySelector('.viewport');
 
    var index = 0;
    function init(){
      ul.style.width = imgs.length * viewport.offsetWidth + 'px';
      //设置li的宽度
      for(var i = 0; i < imgs.length;i++){
        ul.children[i].style.width = viewport.offsetWidth + 'px';
      }
      index --;
      ul.style.left = index * viewport.offsetWidth + 'px';
    }
    init();
    window.addEventListener('resize',function(){
      init();
    });
    var sx,ex;
    ul.addEventListener('touchstart',function(e){
      sx = e.targetTouches[0].clientX;
    })
    ul.addEventListener('touchend',function(e){
      ex = e.changedTouches[0].clientX;
      if(sx < ex){
        //向右
        index ++;
      }else{
        //向左
        index --;
      }
      ul.style.transition = 'all 0.5s linear';
      ul.style.left = index * viewport.offsetWidth + 'px';
      console.log(index)
     
    })
    //当过渡动画结束的时候
    ul.addEventListener('webkitTransitionEnd',function(){
      //左侧边界 
      if(index == 0){
        index = -4;
      }
      //右侧边界
      if(index == -5){
        index = -1
      }
      ul.style.transition = '';
      ul.style.left = index * viewport.offsetWidth + 'px';
    })

    //自动播放
    // var timeID = null;
    // function autoPlay(){
    //   timeID = setInterval(function(){
    //     index--;
    //     ul.style.transition = 'all 0.5 linear';
    //     ul.style.left =  index * viewport.offsetWidth + 'px';
    //   },1000)
    // }
  </script>
</body>
</html>